// components/uploader/uploader.js
const app = getApp()
import {
  policy
} from '../../api/oss'
const util = require('../../utils/util.js')
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    uploadFiles: {
      type: Object,
      value: {}
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    array: ['上传照片', '上传视频'],
    index: 0,
    previewImgs: [],
    images: [],
    previewVideo: [],
    video: "",
    dataObj: {
      policy: '',
      signature: '',
      key: '',
      ossaccessKeyId: '',
      dir: '',
      host: ''
    },
    host: "",
    metaType: 'img',
    uuid: '',
    completed: false,
    metaData: {}
  },

  /**
   * 组件的方法列表
   */
  methods: {
    uploadClick() {
      this.bindPickerChange()
    },
    bindPickerChange: function (e) {
      this.setData({
        index: e.detail.value
      })
      this.beforeUpload()
      if (e.detail.value == 0) {
        this.updataClick()
      } else {
        this.updataVideoClick()
      }
    },
    updataClick() {
      let _this = this;
      _this.data.metaType = 'img'
      wx.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success(res) {
          console.log(res)
          var tempFilePath = res.tempFilePaths
          _this.uploadImg(tempFilePath)
        }
      })
    },
    cancelImgClick(data) {
      var _this = this
      this.data.images.splice(data.target.dataset.index, 1)
      this.setData({
        images: this.data.images
      })
      this.data.metaData = this.data.images.concat(this.data.video);
      var metaData = {
        images: _this.data.images,
        video: _this.data.video,
      }
      _this.triggerEvent("metaClick", metaData)
    },
    cancelVideoClick(data) {
      var _this = this
      this.data.video.splice(data.target.dataset.index, 1)
      this.setData({
        video: this.data.video
      })
      this.data.metaData = this.data.images.concat(this.data.video);
      var metaData = {
        images: _this.data.images,
        video: _this.data.video,
      }
      _this.triggerEvent("metaClick", metaData)
    },
    updataVideoClick() {
      let _this = this;
      _this.data.metaType = 'video'
      var tempFilePath = []
      wx.chooseVideo({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success(res) {
          tempFilePath.push(res.tempFilePath)
          _this.uploadImg(tempFilePath)
        }
      })
    },



    beforeUpload(filePath) {
      let _self = this;
      _self.uuid = util.getUUID()
      policy().then(response => {
        _self.data.dataObj.policy = response.data.policy;
        _self.data.dataObj.signature = response.data.signature;
        _self.data.dataObj.ossaccessKeyId = response.data.accessKeyId;
        _self.data.dataObj.dir = response.data.dir;
        _self.data.dataObj.key = response.data.dir + '/' + _self.uuid + "${filename}";
        _self.data.dataObj.host = response.data.action;
        _self.data.host = response.data.host
        this.uploadImg(filePath)

      }).catch(err => {
        wx.showToast({
          icon: "none",
          title: err.content,
        })
      })
    },
    // 上传图片
    uploadImg(filePath) {
      // debugger
      let _this = this;
      _this.setData({
        uploadPercent: true
      })
      let {
        host,
        ossaccessKeyId,
        policy,
        signature
      } = this.data.dataObj;
      let imgList = [];

      _this.setData({
        images: []
      });
      let resultCount = filePath.length
      filePath.map((item) => {
        // console.log(item)
        // console.log(_this.data.dataObj)
        wx.uploadFile({
          url: host,
          filePath: item,
          name: 'file',
          formData: _this.data.dataObj,
          success: res => {
            // console.log(res)
            if (res.statusCode === 200 || res.statusCode === 204) {
              _this.setData({
                uploadPercent: false
              });
              var fileName = ''
              if (item.indexOf("http://tmp/") != -1) {
                fileName = _this.uuid + item.split('http://tmp/')[1];
              } else if (item.indexOf("wxfile://") != -1) {
                fileName = _this.uuid + item.split('wxfile://')[1];
              }
              // console.log(item)
              if (_this.data.metaType == 'img') {
                _this.data.images.push(_this.data.host + '/' + _this.data.dataObj.dir + '/' + fileName);
                _this.setData({
                  images: _this.data.images
                });
              } else if (_this.data.metaType == 'video') {
                _this.data.video = _this.data.host + '/' + _this.data.dataObj.dir + '/' + fileName
                _this.setData({
                  video: _this.data.video
                });
              }
              // _this.data.metaData = _this.data.images.concat(_this.data.video);
            }
          },
          fail: res => {
            wx.showToast({
              icon: "none",
              title: res.content,
            })
          },
          complete: res => {
            if (!(--resultCount)) {
              if (this.data.completed) {
                this.setData({
                  "metaData.thumbSrc":_this.data.images
                })
                console.log("complete", this.data.metaData)
                _this.triggerEvent("uploaded", this.data.metaData)
                return

              }
              console.log("last", this.data.metaData)
              this.setData({
                metaType: 'img',
                completed: 'true',
                metaData: {
                  images: _this.data.images,
                  video: _this.data.video,                  
                }
              })
              this.uploadImg([this.data.uploadFiles.thumbSrc])
            }
          }
        })
      });
    },
    doUpload() {
      if(!this.data.uploadFiles.type){
        wx.showToast({
          icon:"none",
          title: '请上传照片或视频！',
        })
      }
      this.setData({
        metaType: this.data.uploadFiles.type
      })
      this.beforeUpload(this.data.uploadFiles.filePaths)
    }
  }
})